package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.PushHistoryRepository;
import com.hualude.roadsign.repository.SignalMachineFaultRepository;
import com.hualude.roadsign.repository.UserRepository;
import com.hualude.roadsign.service.SignalMachineCheckService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by ding on 2017/7/22.
 */
@Service
public class SignalMachineCheckServiceImpl implements SignalMachineCheckService {

    @Resource
    private SignalMachineFaultRepository signalMachineFaultRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public DTResponseDto getSignalMachineFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId) throws Exception {
        List<DTMachineFaultDto> dto4DTs = signalMachineFaultRepository.getSignalMachineFault4DT(dtRequestDto, actorId, orgId);
        Integer count = signalMachineFaultRepository.getSignalMachineFaultCount4DT(dtRequestDto, actorId, orgId);
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        for(DTMachineFaultDto dtMachineFaultDto :dto4DTs ){
            String creatorName = userRepository.getUserNameByUserId(dtMachineFaultDto.getMachineCreatorId());
            dtMachineFaultDto.setMachineCreatorName(creatorName);
            String checkerName = userRepository.getUserNameByUserId(dtMachineFaultDto.getMachineCheckerId());
            dtMachineFaultDto.setMachineCheckerName(checkerName);
            if(dtMachineFaultDto.getMachineMainCheckerId()!=null){
                String mainCheckerName = userRepository.getUserNameByUserId(dtMachineFaultDto.getMachineMainCheckerId());
                dtMachineFaultDto.setMachineMainCheckerName(mainCheckerName);
            }
        }
        return dtResponseDto;
    }

    @Transactional
    public Integer machineFaultAudit(Integer isPass, String feedback, Integer machineFaultId, Integer userId) throws Exception {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        Integer check = signalMachineFaultRepository.getMachineCheck(machineFaultId);
        //check:1,主管在审核
        check = (isPass == 2) ? 1 : check;
        if(check==1){
            if(isPass==1||isPass==2){
                final String[] strFaultType = {"损毁", "其他"};
                final SignalMachineFaultDto faultDto = signalMachineFaultRepository.getInfoByFaultId(machineFaultId);
                final Integer orgId = faultDto.getMachineOrgId();
                List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(orgId, 5);
                final String msg = "信号机 NO：" + faultDto.getSignalMachineId() + " " +
                        strFaultType[faultDto.getMachineType()];
                strUserIds = "";
                for (UserDto userDto : userDtos) {
                    strUserIds += userDto.getUserId().toString() + ",";
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!strUserIds.equals("")) {
                                strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                                PushUtil.sendPushToUser(strUserIds, msg);
                                PushHistoryDto pushHistoryDto = new PushHistoryDto(orgId, 5, msg, formatter.format(new Date()),2);
                                pushHistoryRepository.save(pushHistoryDto.toBean());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                if (isPass == 1)
                    return signalMachineFaultRepository.machineFaultAudit2Success(isPass,feedback,machineFaultId,userId,dateNowStr);
                else{
                    return signalMachineFaultRepository.straightFaultAudit(isPass, feedback, machineFaultId, userId, dateNowStr);

                }

            }
            else{
                return signalMachineFaultRepository.machineFaultAudit2Fail(isPass,feedback,machineFaultId,userId,dateNowStr);
            }
        }
        else {
            if(isPass==1){
                final SignalMachineFaultDto faultDto = signalMachineFaultRepository.getInfoByFaultId(machineFaultId);
                List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(faultDto.getMachineMainOrgId(), 7);
                final String msg = "信号机 NO：" + faultDto.getSignalMachineId() + " 待审核";
                strUserIds = "";
                for (UserDto userDto : userDtos) {
                    strUserIds += userDto.getUserId().toString() + ",";
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!strUserIds.equals("")) {
                                strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                                PushUtil.sendPushToUser(strUserIds, msg);
                                PushHistoryDto pushHistoryDto = new PushHistoryDto(faultDto.getMachineMainOrgId(), 7, msg, formatter.format(new Date()),3);
                                pushHistoryRepository.save(pushHistoryDto.toBean());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
            return signalMachineFaultRepository.machineFaultAudit(isPass,feedback,machineFaultId,userId,dateNowStr);
        }
    }

    public List<SignalMachineFaultDto> getMachineFaultCheckList4App(Integer orgId, String actorIds, Integer faultStatus,
                                                                    Integer count, Integer size) throws Exception{
        return signalMachineFaultRepository.getMachineFaultCheckList4App(orgId, actorIds, faultStatus, count, size);
    }

}
